var Elm = {};
var px = px;

function debug() {
    var test = 'test';
    test = 'test';
}



String.prototype.gReplace = function(what, replace) {
    return this.split(what).join(replace);
}


function arrayGetValue(arr, key, defVal) {
    arr = arr || [];
    if (typeof(key) == 'undefined') key = false;
    else key = key || false;
    defVal = defVal || null;
    
    if (key === false) return defVal;
    if (arr.hasOwnProperty(key)) return arr[key];
    else return defVal;
}


function Request(url, postData, dataType, onSuccess, onError) {
    var today = new Date();
    var nc = today.getTime().toString() + "_" + Math.random().toString();

    if (url.indexOf('?')>=0) nc = '&'+nc;
    else nc = '?'+nc;


    var json = (dataType=='json')? '&jsoncb=?':'';


    var settings = {
          type: 'POST',
          url: url+nc+json,
          data: postData,
          dataType: dataType
        }

    var xhr = $.ajax(settings);

    xhr.success(function(data) {
        if (typeof(onSuccess) == 'function') onSuccess(data);
        xhr = null;
        data = null;
    });

    xhr.error(function(data) {
        if (typeof(onError)   == 'function') onError(data);
        xhr = null;
        data = null;
    });
}


function htmlRequest(url, postData, onSuccess, onError) {
    Request(url, postData, 'html', onSuccess, onError);
}


function jsonRequest(url, postData, onSuccess, onError) {
    Request(url, postData, 'json', onSuccess, onError);
};


function uiAlert(msg,title) {
    title = title || ' ';
    msg = msg || '';
    var d = $('<div>').
        html(msg).
        dialog({
            modal       : true,
            resizable   : false,
            title       : title,
            autoOpen    : true,
            zIndex      : 10000,
            buttons     : {"Оk"    : function() {$(this).dialog("close").remove();}}
        });

    d.dialog('widget').find('button.ui-button').attr('class', 'btn');
}

function uiConfirm(inpParams) {
    inpParams = inpParams || {};
    var params = {
        title : 'Подтверждение',
        text :  'Выполнить действие?',
        ok :    function(){},
        cancel: function(){}
    };
    
    $.extend(params, inpParams);
    
    var today = new Date();
    params.id = today.getTime().toString()+"_"+Math.random().toString().gReplace('.', '');
    
    var html = fillTemplate('#uiConfirm-tmpl', params);
    $('body').append(html);
    
    var C = $('#uiConfirm-cont-'+params.id);
    C.dialog({
            width       : 350,
            modal       : true,
            resizable   : false,
            title       : params.title,
            autoOpen    : true,
            zIndex      : 10000
        }).removeClass('hidden');
    C.dialog('widget').find('a.ui-dialog-titlebar-close').hide(); // прячем крестик 
    
    $('#uiConfirm-submit-'+params.id).click(function() {
        if (typeof(params.ok) == 'function') params.ok();
        C.dialog('close').remove();
    });
    
    $('#uiConfirm-cancel-'+params.id).click(function() {
        if (typeof(params.cancel) == 'function') params.cancel();
        C.dialog('close').remove();
    });
}



function cryptPass() {
    var pp = $('#pass_plain');
    var pass = calcMD5(calcMD5(pp.val())+$('#token').val());
    pp.val('');
    $('#pass').val(pass);
    return pass;
}



function checkSession(jsonData) {
    if(jsonData.hasOwnProperty('logged') && jsonData.logged) return true;
    if (jsonData.hasOwnProperty('token')) $('#token').val(jsonData.token);
    return false
}






//#####################################################################
$(function(){
    Elm.body = $('body');
    Elm.loginForm = $('#loginForm');
    Elm.loginFormModal = $('#loginFormModal');
    Elm.loginFormModal.successCallback = function(){};

    Elm.body.addClass('jqgray');

    Elm.loginFormModal.dialog({
        width       : 300,
        modal       : true,
        resizable   : false,
        title       : "Повторный вход в систему",
        autoOpen    : false,
        zIndex      : 20000,
        buttons     : {}
    });


    Elm.loginForm.submit(function(e){ cryptPass(); });
    Elm.loginFormModal.submit(function(e){
        var pass = cryptPass();

        var send = Elm.loginFormModal.serialize();
        jsonRequest(
            'login.php',
            send,

            function(data) {
                if(checkSession(data)) {
                    Elm.loginFormModal.dialog('close');
                    if (typeof(Elm.loginFormModal.successCallback == 'function')) Elm.loginFormModal.successCallback();
                }
                else uiAlert('Ошибка авторизации','Error');
            },

            function() {
                uiAlert('Ошибка соединения','Error');
            }
        );
            return false;
    });
});



function ovlAlert(html) {
    $('#ovl .ovl-place').html(html);
    $('#ovl').show();
}

function ovlClose() {
    $('#ovl .ovl-place').empty();
    $('#ovl').hide();
}

function reloadCntList(cont) {
    cont.load('contacts.php?getList');
}


function formatGenderToInt(g) {
    if ((g*1 == 0)||(g == 'f')) return 0;
    if ((g*1 == 1)||(g == 'm')) return 1;
    return -1;
}


function formatGenderToChar(g) {
    if ((g*1 == 0)||(g == 'f')) return 'f';
    if ((g*1 == 1)||(g == 'm')) return 'm';
    return '0';
}


function formatRating(rating) {
    rating = rating || 0;
    if (rating*1 == 0) return ' 0';

    if (rating*1 > 5) rating = 5;
    if (rating*1 > 0) return '+'+rating;

    if (rating < -5) return -5;
    return rating;
}


 // Функция генерации случайного набора символов
function rndString(strLen) {
    // Из каких символов будет собирать строку
    symbols = "abcdefghijklmnopqrstuvwxyz";
	var result = "";
	for (var i=0; i<strLen; i++) {
		result += symbols.charAt(Math.floor(Math.random()*symbols.length));
	};
	return result;
}


function fillTemplate (tmpl, data) {
    tmpl = tmpl || '#none';
    data = data || {};
    
    var html = $(tmpl).html();
    html = html || '';
    
    for (var i in data) {
        if (!data.hasOwnProperty(i)) continue;
        html = html.gReplace('{%'+i+'%}', data[i]);
    }
    
    return html;
}




function StopWatch() {
    this.callback = function() {};

    this.startDate = 0;
    this.interval = 0;
    this.running = false;




    this.Start = function (callback) {
        if (this.running) this.Stop();
        this.startDate = new Date();
        this.callback = (typeof(callback) == 'function')? callback : function() {};
        this.running = true;
        this._Process();
    };

    this.Stop = function () {
        this.running = false;
        if(this.interval) clearTimeout(this.interval);
    };





    this._Process = function() {
        if (!this.running) return;
        var cDate = new Date();
        var timesec = Math.floor((cDate.getTime() - this.startDate.getTime())/1000);

        var h = this._LeadZero(Math.floor(timesec/3600));
        var lost = timesec%3600;
        var m = this._LeadZero(Math.floor(lost/60));
        var s = this._LeadZero(lost%60);

        var th = this;
        this.interval = setTimeout(function() {th._Process()}, 1000);
        this.callback({h:h,m:m,s:s});
    };

    this._LeadZero = function(number) {
        if (number*1>=0 && number*1<=9) return '0'+(number*1); 
        else return number*1;
    };


};